<?php
/**
 * Created by PhpStorm.
 * User: qhzhyt
 * Date: 2018/10/9
 * Time: 21:40
 */

if (!isset($_POST['status']) || !isset($_POST['mapId'])) {
    echo(json_encode(['status' => 0, 'code' => 2]));
    exit(1);
}
session_start();
if (!isset($_SESSION['user'])) {
    echo(json_encode(['status' => 0, 'code' => -1]));
    exit(1);
}

$user = $_SESSION['user'];
$status = $_POST['status'];
$mapId = $_POST['mapId'];

require_once '../conf/conf.php';

if ($status == 'S') {
    if (!isset($_POST['takeTime']) || !isset($_FILES['record'])) {
        echo(json_encode(['status' => 0, 'code' => 2]));
        exit(1);
    }

    $takeTime = $_POST['takeTime'];
    $record = $_FILES['record'];
    if (!is_uploaded_file($record['tmp_name'])) {
        echo(json_encode(['status' => 0, 'code' => 2]));
        exit(1);
    }

    $file_hash = md5_file($record['tmp_name']);

    $db->insert('play_record', [
        'user_id' => $user['user_id'],
        'map_id' => $mapId,
        'take_time' => $takeTime,
        'status' => $status,
        'record_hash' => $file_hash
    ]);

    if ($db->id() == 0) {
        echo(json_encode(['status' => 0, 'code' => 2]));
        exit(0);
    }


    $fileName = $mapId . /*'_' . $user['user_id'] .*/ '_' . substr($file_hash, 0, 6) . '.rec';

    move_uploaded_file($record['tmp_name'], '../files/upload/record/' . $fileName);

} else {

    $db->insert('play_record', [
        'user_id' => $user['user_id'],
        'map_id' => $mapId,
        'status' => $status,
    ]);
    if ($db->id() == 0) {
        echo(json_encode(['status' => 0, 'code' => 2]));
        exit(0);
    }
}
$exp = $user['challenge_exp'];

$level = $user['challenge_level'];
if ($status == 'S') {
    $exp += 5;
    $user['win_count'] = $user['win_count'] + 1;
} else
    $exp += 1;

$need = pow(2, $level) * 5;

if ($exp >= $need) {
    $exp -= $need;
    $user['challenge_level'] = $level + 1;
}

$user['challenge_exp'] = $exp;
$user['challenge_count'] = $user['challenge_count'] + 1;

$db->update('user', [
    'challenge_exp' => $user['challenge_exp'],
    'challenge_level' => $user['challenge_level'],
    'challenge_count' => $user['challenge_count'],
    'win_count' => $user['win_count']
], ['user_id' => $user['user_id']]);
echo(json_encode(['status' => 1, 'code' => 1]));